﻿using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class RectGuide : GuideBase
{
    private float _width;
    private float _height;

    private Transform _guide;
    private TextMeshProUGUI _text;

    private Canvas _canvas;
    private RectTransform _target;

    public void Init(int index, Canvas canvas, RectTransform target, Action<int> doneAction)
    {
        _index = index;
        _canvas = canvas;
        _target = target;
        _doneAction = doneAction;
    }

    public void Show(string guide)
    {
        Guide(_canvas, _target, 10, 0.2f);

        _text.text = $"{guide}";
    }

    public override void Guide(Canvas canvas, RectTransform target)
    {
        base.Guide(canvas, target);
        _guide = transform.Find("Guide");
        _text = transform.Find("Guide/Text").GetComponent<TextMeshProUGUI>();

        _guide.gameObject.SetActive(true);

        _width = (_targetCorners[3].x - _targetCorners[0].x) / 2;
        _height = (_targetCorners[1].y - _targetCorners[0].y) / 2;

        //设置宽和高
        _material.SetFloat("_SliderX", _width + 20);
        _material.SetFloat("_SliderY", _height + 20);

        //设置文本位置
        RectTransform parentRect = _guide.GetComponent<RectTransform>();

        Vector2 pivot = new Vector2();
        pivot.x = target.localPosition.x > 0 ? 1 : 0;
        pivot.y = target.localPosition.y > 0 ? 1 : 0;
        float x = target.localPosition.x > 0 ? -target.rect.width / 2 - 40 : target.rect.width / 2 + 40;
        float y = target.localPosition.y > 0 ? target.rect.height / 2 : -target.rect.height / 2;
        parentRect.pivot = pivot;
        parentRect.localPosition = new Vector3(target.localPosition.x + x, target.localPosition.y + y, 0);
    }

    public void Guide(Canvas canvas, RectTransform target, float frameWidth, float time)
    {
        Guide(canvas, target);
        _guide.gameObject.SetActive(false);
        Vector2 size = new Vector2(Screen.width, Screen.height);
        Vector2 targetSize = new Vector2(_width + frameWidth, _height + frameWidth);

        DOTween.To(() => size, (value) => size = value, targetSize, time)
            .SetEase(Ease.Linear)
            .OnUpdate(() =>
            {
                _material.SetFloat("_SliderX", size.x);
                _material.SetFloat("_SliderY", size.y);
            })
            .OnComplete(() => { _guide.gameObject.SetActive(true); });
    }

    public override void OnMaskButtonClick()
    {
        base.OnMaskButtonClick();
        _doneAction?.Invoke(_index);
    }
}